<template>
  <el-dialog
    :model-value="roleDialogVisible"
    :title="roleDialogTitle"
    width="30%"
    @close="handleClose"
  >
    <el-form
      :model="form"
      label-width="80px"
      :rules="rules"
      ref="ruleFormRef"
      status-icon
    >
      <el-form-item label="角色姓名" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="角色备注" prop="roleRemark">
        <el-input v-model="form.roleRemark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleConfirm">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus/lib/components'
import { defineEmits, defineProps, ref, watch } from 'vue'
import { getAllRoleList, addOrModifyRole } from '@/api/authority.js'

const initForm = () => {
  return {
    roleName: '',
    roleRemark: '',
    id: ''
  }
}

const ruleFormRef = ref(null)
const form = ref(initForm())

// 一定要注意顺序，需要先声明响应式
const props = defineProps({
  roleDialogValue: {
    type: Object,
    require: true,
    default: () => {}
  },
  roleDialogVisible: {
    type: Boolean,
    require: true,
    default: false
  },
  roleDialogTitle: {
    type: String,
    default: '',
    required: true
  }
})
watch(
  () => props.roleDialogValue,
  // 切记如果使用一个一个赋值就不是响应式了，就会出现原来的数据还存在
  () => {
    form.value = props.roleDialogValue
  },
  {
    deep: true,
    immediate: true
  }
)
const emits = defineEmits(['update:modelValue', 'initTableList'])

const validatePass = (rule, value, callback) => {
  if (value === '') {
    return callback(new Error('请输入角色名'))
  }
  setTimeout(async () => {
    if (props.roleDialogTitle === '添加角色') {
      const res = await getAllRoleList()
      const roleNameList = res.data.map((item) => item.roleName)
      if (roleNameList.includes(form.value.roleName)) {
        callback(new Error('该角色已存在请重新输入'))
        form.value = initForm()
      } else {
        callback()
      }
    } else {
      callback()
    }
  }, 1000)
}

const rules = ref({
  roleName: [
    {
      validator: validatePass,
      trigger: 'blur'
    }
  ],
  roleRemark: [
    {
      required: true,
      message: 'Please input roleRemark',
      trigger: 'blur'
    }
  ]
})

const handleClose = () => {
  Object.assign(form.value, initForm())
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      // console.log(form.value)
      try {
        await addOrModifyRole(form.value)
        ElMessage({
          type: 'success',
          message:
            props.roleDialogTitle === '添加角色' ? '添加成功' : '修改成功',
          duration: 1500
        })
        handleClose()
        emits('initTableList')
      } catch (error) {
        ElMessage({
          type: 'error',
          message: error,
          duration: 1500
        })
      }
    } else {
      console.log('error confirm!!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped></style>
